package com.ego.upload.service.impl;

import com.ego.upload.service.UploadService;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
@Service
@Slf4j
public class UploadServiceImpl implements UploadService {

    @Autowired
    private FastFileStorageClient storageClient;
   // private final Logger logger= LoggerFactory.getLogger(UploadService.class);
    private List<String> suffixs= Arrays.asList("png","jpg");
    //上传图片
    @Override
    public String uploadImage(MultipartFile file) {
        //1.判断是不是图片后缀(png,jpg)
        String suffix = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
        if(!suffixs.contains(suffix)){
            return null;
        }
        //2.判断是不是图片内容
        try {
           if(ImageIO.read(file.getInputStream())==null){
               return null;
           }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("验证图片出错");
            return null;
        }
        //3.保存图片到硬盘(d://test)
        String fullPath=null;
        try {
//            File dir = new File("d://test/");
//            if(!dir.exists()){
//                dir.mkdirs();
//            }
//            file.transferTo(new File("d://test/"+file.getOriginalFilename()));
          StorePath storePath=storageClient.uploadFile(file.getInputStream(),file.getSize(),suffix,null);
            fullPath = storePath.getFullPath();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("保存图片到硬盘出错");
            return null;
        }
        //4.拼接路径(http://image.ego.com/xxx.png)
        return "http://image.ego.com/"+fullPath;
    }
}
